package com.amithkoujalgi.framework.rest.util;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.amithkoujalgi.framework.rest.core.ApplicationContext;

public class ConfigValidator
{
	private static Logger logger = Logger.getLogger( ConfigValidator.class );

	@SuppressWarnings("rawtypes")
	public static boolean checkForConfigKeys( String[] keys, boolean exitOnFail ) throws Exception
	{
		List<String> configKeys = new ArrayList<String>( Arrays.asList( keys ) );
		List<String> loadedProps = new ArrayList<String>();
		for( Entry e : com.amithkoujalgi.framework.rest.core.ApplicationContext.getInstance().getConfig().entrySet() )
		{
			for( String cfgKey : configKeys )
			{
				loadedProps.add( (String) e.getKey() );
			}
		}
		List<String> found = new ArrayList<String>();
		for( String loadedProp : loadedProps )
		{
			for( String keyCheck : configKeys )
			{
				if( keyCheck.equals( loadedProp ) )
				{
					found.add( keyCheck );
				}
			}
		}
		configKeys.removeAll( found );
		if( configKeys.isEmpty() )
		{
			return true;
		}
		String missing = "";
		for( String missingKey : configKeys )
		{
			missing = missing + ", '" + missingKey + "'";
		}
		missing = missing.trim();
		if( missing.startsWith( "," ) )
		{
			missing = missing.substring( 1, missing.length() );
		}
		if( missing.endsWith( "," ) )
		{
			missing = missing.substring( 0, missing.length() - 1 );
		}
		if( exitOnFail )
		{
			logger.error( "Config key/s missing: " + missing.trim() );
			logger.error( "Terminating app..." );
			System.exit( 0 );
			return false;
		}
		else
		{
			throw new Exception( "Config key/s missing: " + missing.trim() );
		}
	}

	/**
	 * If the given configKey is null or not found, the default value will be
	 * substituted.
	 * 
	 * @param configKey
	 * @param defaultValue
	 */
	public static String loadDefaultIfConfigPropNotFound( String configKey, String defaultValue )
	{
		String val = ApplicationContext.getInstance().getConfig().getProperty( configKey );
		if( val == null )
		{
			val = defaultValue;
			logger.info( "Config property '" + configKey + "' not found. Using default value '" + defaultValue + "'" );
			ApplicationContext.getInstance().getConfig().put( configKey, val );
		}
		return val;
	}
}
